package com.alander.nexusgo.im.mapper;

import com.alander.nexusgo.im.model.entity.SingleMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface SingleMessageMapper extends BaseMapper<SingleMessage> {
    
    /**
     * 查询两个用户之间的消息记录
     * @param userId1 用户1 ID
     * @param userId2 用户2 ID
     * @return 消息列表
     */
    default List<SingleMessage> selectMessagesBetweenUsers(Long userId1, Long userId2) {
        LambdaQueryWrapper<SingleMessage> wrapper = Wrappers.lambdaQuery(SingleMessage.class)
            .and(w -> w.eq(SingleMessage::getSenderId, userId1).eq(SingleMessage::getReceiverId, userId2))
            .or(w -> w.eq(SingleMessage::getSenderId, userId2).eq(SingleMessage::getReceiverId, userId1))
            .orderByAsc(SingleMessage::getCreateTime);
        return selectList(wrapper);
    }
    
    /**
     * 查询用户未读消息
     * @param receiverId 接收者ID
     * @return 未读消息列表
     */
    default List<SingleMessage> selectUnreadMessages(Long receiverId) {
        LambdaQueryWrapper<SingleMessage> wrapper = Wrappers.lambdaQuery(SingleMessage.class)
            .eq(SingleMessage::getReceiverId, receiverId)
            .eq(SingleMessage::getStatus, 0)
            .orderByAsc(SingleMessage::getCreateTime);
        return selectList(wrapper);
    }
    
    /**
     * 标记消息为已读
     * @param receiverId 接收者ID
     * @param senderId 发送者ID
     * @return 更新记录数
     */
    default int updateMessagesAsRead(Long receiverId, Long senderId) {
        LambdaQueryWrapper<SingleMessage> wrapper = Wrappers.lambdaQuery(SingleMessage.class)
            .eq(SingleMessage::getReceiverId, receiverId)
            .eq(SingleMessage::getSenderId, senderId)
            .eq(SingleMessage::getStatus, 0);
        
        SingleMessage updateEntity = new SingleMessage();
        updateEntity.setStatus(1);
        return update(updateEntity, wrapper);
    }
}